package es.android.lottoscan;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.util.Log;

public class LottoCheck implements Runnable {

	public static String TAG = "LottoCheck";

	LottoData data;
	LottoCheckListener listener;

	public void query(LottoData data, LottoCheckListener listener) {
		this.data = data;
		this.listener = listener;
		Thread thread = new Thread(this);
		thread.start();
	}

	/**
	 * Gets data from server
	 */
	public void run() {
		boolean error = false;
		String prize = null;
		
		try {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(data.getDate());
			String url = "http://www.onlae.es/loteria/comprobar.aspx";
			Log.d(TAG, url);

			InputStream is = openHttpConnection(url);
			String dataString = convertStreamToString(is);
			//Log.d(TAG, dataString);

			// Now we need to get __VIEWSTATE & __EVENTVALIDATION from the
			// response
			String viewState = null;
			Pattern viewStatePattern = Pattern.compile("<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"(.*)\" />");
			Matcher viewStateMatcher = viewStatePattern.matcher(dataString);
			if (viewStateMatcher.find())
				viewState = viewStateMatcher.group(1);

			String eventValidation = null;
			Pattern eventValidationPattern = Pattern.compile("<input type=\"hidden\" name=\"__EVENTVALIDATION\" id=\"__EVENTVALIDATION\" value=\"(.*)\" />");
			Matcher eventValidationMatcher = eventValidationPattern.matcher(dataString);
			if (eventValidationMatcher.find())
				eventValidation = eventValidationMatcher.group(1);

			Log.d(TAG, "viewState = " + viewState);
			Log.d(TAG, "eventValidation = " + eventValidation);

			// De momento sólo vale para 2010 TODO
			int date = 880 + data.getDateAsNumber();
			
			String postData =
				"__EVENTTARGET=" +
				"&__EVENTARGUMENT=" +
				"&__LASTFOCUS=" +
				"&__VIEWSTATE=" + URLEncoder.encode(viewState,"UTF-8") +
				"&ctl00%24mainContent%24ucFechasSorteos%24ddlFechas=" + date +
				"&ctl00%24mainContent%24ucComprobar%24txtNumero=" + data.getNumber() +
				"&ctl00%24mainContent%24ucComprobar%24txtFraccion=" + data.getFractionNumber() +
				"&ctl00%24mainContent%24ucComprobar%24txtSerie=" + data.getSerialNumber() +
				"&ctl00%24mainContent%24ucComprobar%24txtNumero2=" +
				"&ctl00%24mainContent%24ucComprobar%24txtFraccion2=" +
				"&ctl00%24mainContent%24ucComprobar%24txtSerie2=" +
				"&ctl00%24mainContent%24ucComprobar%24txtNumero3=" +
				"&ctl00%24mainContent%24ucComprobar%24txtFraccion3=" +
				"&ctl00%24mainContent%24ucComprobar%24txtSerie3=" +
				"&ctl00%24mainContent%24ucComprobar%24txtNumero4=" +
				"&ctl00%24mainContent%24ucComprobar%24txtFraccion4=" +
				"&ctl00%24mainContent%24ucComprobar%24txtSerie4=" +
				"&ctl00%24mainContent%24ucComprobar%24txtNumero5=" +
				"&ctl00%24mainContent%24ucComprobar%24txtFraccion5=" +
				"&ctl00%24mainContent%24ucComprobar%24txtSerie5=" +
				"&ctl00%24mainContent%24ucComprobar%24btnComprobar=Comprobar" +
				"&__EVENTVALIDATION=" + URLEncoder.encode(eventValidation, "UTF-8");
			Log.d(TAG, "POSTDATA="+postData);
			is = openHttpPostConnection(url, postData);
			dataString = convertStreamToString(is);
			//Log.d(TAG, dataString);

			// <strong class='premiado'>30.000,00 €</strong>

			Pattern prizePattern = Pattern.compile("<strong class='premiado'>(.*)</strong>");
			Matcher prizeMatcher = prizePattern.matcher(dataString);
			if (prizeMatcher.find()) {
				prize = prizeMatcher.group(1);
			}

		} catch (Exception e) {
			Log.e(TAG, "There was an error", e);
			error = true;
		}
		if (listener != null) {
			if (error) {
				listener.checkError();
			} else {
				listener.checkOk(prize);
			}
		}
	}

	public String convertStreamToString(InputStream is) throws IOException {
		Log.e(TAG, "convertStreamToString()");
		if (is != null) {
			StringBuilder sb = new StringBuilder();
			String line;

			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "UTF-8"));
				while ((line = reader.readLine()) != null) {
					sb.append(line).append("\n");
				}
			} finally {
				is.close();
			}
			return sb.toString();
		} else {
			Log.e(TAG, "Error obtaining data!!!");
			return null;
		}
	}

	private InputStream openHttpConnection(String urlString) throws IOException {
		InputStream in = null;
		int response = -1;

		URL url = new URL(urlString);
		URLConnection connection = url.openConnection();

		if (!(connection instanceof HttpURLConnection))
			throw new IOException("Not an HTTP connection");

		try {
			HttpURLConnection httpConn = (HttpURLConnection) connection;
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			httpConn.connect();
			response = httpConn.getResponseCode();
			
			System.out.println(httpConn.getHeaderFields());
			if (response == HttpURLConnection.HTTP_OK) {
				in = httpConn.getInputStream();
			}
		} catch (Exception ex) {
			throw new IOException("Error connecting");
		}
		return in;
	}

	private InputStream openHttpPostConnection(String targetURL, String urlParameters) throws IOException {
		InputStream in = null;
		int response = -1;

		// Create connection
		URL url = new URL(targetURL);
		URLConnection connection = url.openConnection();

		if (!(connection instanceof HttpURLConnection))
				throw new IOException("Not an HTTP connection");

		try {
			HttpURLConnection httpConn = (HttpURLConnection) connection;
			httpConn.setRequestMethod("POST");
			httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			httpConn.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
			httpConn.setUseCaches(false);
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);

			// Send request
			DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
			wr.writeBytes(urlParameters);
			wr.flush();
			wr.close();

			// Get Response
			response = httpConn.getResponseCode();
			Log.d(TAG, "Http Response=" + response);
			if (response == HttpURLConnection.HTTP_OK) {
				in = httpConn.getInputStream();
			}

		} catch (Exception e) {
			throw new IOException("Error connecting");
		}
		return in;
	}

	public void setListener(LottoCheckListener listener) {
		this.listener = listener;
	}
}
